//
//  ZYLoginViewModel.m
//  YiLin
//
//  Created by Zyark on 2018/6/12.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYLoginViewModel.h"
#import "ZYBasicHelper.h"
#import "AFNetWorkUtils.h"
#import "ZYUser.h"

@interface ZYLoginViewModel()
@property(nonatomic,strong) RACSignal *enableLoginSignal;
@end

@implementation ZYLoginViewModel

-(RACCommand *)loginCommand{
    if(!_loginCommand){
        _loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            NSDictionary *params = @{@"password":self.password,@"phone":self.username};
            NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_LOGIN_URL];
            @weakify(self);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                if(NULLString(self.password)){
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PASSWORD_EMPTY]]];
                    [subscriber sendCompleted];
                    return nil;
                }
                if(NULLString(self.username)){
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PHONE_OR_USERNAME_EMPTY]]];
                    [subscriber sendCompleted];
                    return nil;
                }
                [[AFNetWorkUtils racPOSTWithURL:url params:params] subscribeNext:^(id x) {
                    NSDictionary *responseObject = x;
                    ZYUser *user = [ZYUser modelWithJSON:[responseObject objectForKey:@"result"]];
                    [ZYConfig saveUserInfo:user];
                    [subscriber sendNext:x];
                    [subscriber sendCompleted];
                } error:^(NSError *error) {
                    [subscriber sendError:error];
                    [subscriber sendCompleted];
                }];
                return nil;
            }];
        }];
    }
    return _loginCommand;
}

@end
